package cn.com.bluemoon.daps.common.datascope.sign;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author Lilike on 2022/2/21
 */
public class CommonReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public CommonReaderHttpServletRequestWrapper(HttpServletRequest request, String bodyStr) throws IOException {
        super(request);
        //将header中的的数据缓存到字节数组中，以后要读数据就用这里的
        body = getRequestPostBytes(request, bodyStr);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        /**
         * 从缓存的数据中读取数据
         */
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
            }
        };
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request, String bodyStr) throws IOException {
        return bodyStr.getBytes(StandardCharsets.UTF_8);
    }

}
